/*
*	javascript for mclient
*
**/
//(function (){

	var intervalGetNext = null ;
	var intervalTimeOut = null ;
	var intervalSendAnswer = null ;
	var stopGetNext = true ;
	var getNextCount = 0 ;
	var maxLocalCacheSize = 2 ;
	var key = "123456";
	var pwd="123456";
	var clientId=42;
	var sendAnswerTimes=0;
	if(typeof String.prototype.trim !== 'function') {
	  String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g, ''); 
	  }
	}
	function setKey(uKey){
		key=uKey;
	}
	function setPwd(uPwd){
		pwd = uPwd;
	}
	function setClientId(id){
		clientId=id;
	}
	function show(o) {
  		var timenow = new Date().getTime();
  		o.src = "validatecode?d=" + timenow;
	}	
	function showError(errMsg){
		$("#errMsg").html(errMsg);
	}
	function getCount(){		
		
		var clientId = $("input#clientId").val();
		try
		{
			$.ajax({
				url:'client',
				type:"get",
				data:{
					"actionType":"getCount",
					"clientId":clientId
				},
				dataType:"json",
				success:function(data,textStatus){
					$.each(data,function(i,element){
						$("#answerCount").html(element.answerCount);
						$("#wrongCount").html(element.wrongCount);
						$("#point").html(element.point);
						$("#waitCount").html(element.waitCount);
					});
				}
			});
		}
		catch(e){
			showError(e);
		}
		return false ;	
	}
	function sound(){
		document.getElementById('snd').src = 'audio/alarm.mp3';
	}
	function next(){
		$("input#answer").show();
		$("input#answer").val('');
		$("input#answer").focus();
		$("#msgId").html('');
		$("#answerLen").html('');
		$("#answerType").html('');
		$("#gameType").html('');
		$("#timeOut").html('');
	
		// 如果缓冲区有图片，加载第一张
		var msgList = $("div#msgList>div");
		if(msgList.length > 0)
		{
			var nextMsg = msgList.get(0);
			// 清空原来的区域
			$("div#main").html("");
			$("div#main").append(nextMsg);
			var id = nextMsg.attributes.getNamedItem("id").value;
			var answerLen = nextMsg.attributes.getNamedItem("answerLen").value;
			var answerType = nextMsg.attributes.getNamedItem("answerType").value;
			var gameType = nextMsg.attributes.getNamedItem("gameType").value;
			var timeOut = nextMsg.attributes.getNamedItem("timeOut").value;

			$("input#answer").val('');
			$("input#answer").focus();
			$("#msgId").html(id);
			$("#answerLen").html(answerLen);
			$("#answerType").html(answerType);
			$("#gameType").html(gameType);
			$("#timeOut").html(timeOut);
			$("#answerDescription").html(answerType);
			$('span#msgId'+id).remove();
			if (warning)
				sound();	
				
		}
		else
		{
			$("input#answer").val('');
			$("input#answer").hide();
		}
		$("#bufCount").html($("div#msgList>div").length);
	}

	function getNext(){
		
		if($('div#main').html() == '')
			next();
			
		if (stopGetNext)
			return ;
						
		var bufSize = $("div#msgList>div").length;
//		if(bufSize >= maxLocalCacheSize)
//			return ;
		var msgCount = maxLocalCacheSize - bufSize ;
		var clientId = $("input#clientId").val();
		var getTimes = getNextCount;
		try
		{
			$.ajax({
				timeout:3500,
				url:'client',
				type:"get",
				cache:false,
				data:{
					"actionType":"getMsg",
					"clientId":clientId,
					"msgCount":msgCount,
					"getNextCount":getTimes,
					"key":key,
					"password":pwd
				},
				dataType:"json",
				success:function(data,textStatus){
					$("#answerCount").html(data[0].answerCount);
					$("#wrongCount").html(data[0].wrongCount);
					$("#point").html(data[0].point.toFixed(2));
					$("#waitCount").html(data[0].waitCount);
					
					var accuracyRate = 100.00 ;
					if (data[0].answerCount > 0)
						accuracyRate = ((1.0 - 1.0*data[0].wrongCount/data[0].answerCount)*100).toFixed(2) ;
					$("#accuracyRate").html(accuracyRate+'%');
					$.each(data[0].msg,function(i,element){
						
						var id = element.msgId;
						var innerHTML = '<div width=600 height=400  action="user" id='+id+' answerLen='+element.answerLen
									+' answerType="'+ element.answerType + '" gameType='+element.gameType+' timeOut='+element.timeOut
									+' recvTime=' + element.recvTime + ' interval=' + element.interval
									+' >'
						            +'<p><img src="file?actionType=getFile&msgId='+id+'"/></p>'
						      	+'</div>';
							$("div#msgList").append(innerHTML);
						innerHTML = '<span id=msgId'+id+'>'+id+',</span>';
						$("div#msgIdList").append(innerHTML);			      	
						  
					});
					$("#bufCount").html($("div#msgList>div").length);
					getNextCount++ ;
					
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
        		//TODO: 处理status， http status code，超时 408
        		// 注意：如果发生了错误，错误信息（第二个参数）除了得到null之外，还可能
              	//是"timeout", "error", "notmodified" 和 "parsererror"。
              		logger('取题异常'+(getTimes)+textStatus);
        		}
				
			});
		}
		catch(e){
			showError(e);
		}
		return false ;
	}
	function logout(){
		if(confirm("请确认已暂停答题，并且本地队列题数为0"))
		{
			window.location.href='client';
		}
	}
	function queryWrongAnswerRecord(){
		alert('暂未实现');
	}
	function logger(errMsg){
		var msgText = '<span>'+errMsg+' , </span>'
		$("div#logger").append(msgText);
	}
	function clearLogger(){
		$("div#logger").html('异常日志:');
	}
	function timeout(){
		var timeout = $('#timeOut');
		if(timeout)
		{
			var time = timeout.html();
			if (time)
			{var seconds = eval(time);
			$('#timeOut').html(seconds -1);
			}
		}
		/*var msgList = $("div#msgList>div");
		if (msgList.length <= 0)
			return ;
		for(var i = 0 ; i < msgList.length; i++)
		{
			var nextMsg = msgList.get(0);
			var time = nextMsg.attributes.getNamedItem("timeOut").value;
			time = eval(time)-1;
			nextMsg.prop('timeOut',time);
		}*/
		$("div#msgList>div").attr('timeOut',function(i,oldValue){
			var time = eval(oldValue);
			return time - 1 ;
		});
		
		
	}
	var warning = false ;
	function startWarning(){
		warning = !warning ;
		if(warning)
			$("input#btnStartWarning").val("来题静音");
		else
			$("input#btnStartWarning").val("来题报警");
	}
	function focusAnswerInput(){
		$("input#answer").focus();
	}
	function startAnswer(){
		if (stopGetNext)
		{
			clearLogger();
			$("input#answer").val("");
			$("div#main").html("");
			stopGetNext = false ;
			
			if (!intervalGetNext)
				intervalGetNext = setInterval(getNext,1000);
			if (!intervalTimeOut)
				intervalTimeOut = setInterval(timeout,1000);
			if (!intervalSendAnswer)
				intervalSendAnswer = setInterval(sendAnswersBg,500);
			
			
			$("input#btnStartAnswer").val("暂停答题");
			var doFocus = setTimeout(focusAnswerInput,50);
		}
		else
		{
			stopGetNext = true ;
			$("input#btnStartAnswer").val("开始答题");
			
			if (intervalTimeOut)
			{	
				clearInterval(intervalTimeOut);
				intervalTimeOut = null ;
			}
			var doFocus = setTimeout(focusAnswerInput,50);
		}
	}
	function sendAnswerByKey(event,element)
	{
		var contentDiv = $("div#main>div");
		if (!contentDiv || !contentDiv.get(0))
			return ;
		var id = contentDiv.get(0).attributes.getNamedItem("id").value;
		var answerLen = contentDiv.get(0).attributes.getNamedItem("answerLen").value;
		var length = element.value.length ;
		var evt=event?event:(window.event?window.event:null);

		if (length == answerLen || evt.keyCode == 13)
		{
			sendAnswer(id);
			// 清空原来的区域
			$("div#main").html("");
			// 获取下一张图片
			next();
		}
		return false ;
	}
	function sendAnswersBg(){
		var answerList = $('div#answerList>span');
		if (answerList.length > 0)
		{
			var msgIds = new Array() ;
			var answers = '' ;
			var i = 0 ;
			for(; i < answerList.length && i < 5 ; i++)
			{
				var answerPair = answerList.get(i);
				var msgId = answerPair.attributes.getNamedItem("msgId").value;
				var answer = answerPair.attributes.getNamedItem("answer").value;
				answer=encodeURI(answer);
				if (i > 0)
					answers += '#'
				answers += msgId + ':' + answer ;
				msgIds[i] = msgId ;
			}
			sendAnswerTimes++;
			try
			{
				$.ajax({
					type:"post",
					url:"client",
					cache:false,
					timeout:3000,
					data:{
					"actionType":"sendAnswers",
					"answers":answers,
					"password":pwd,
					"clientId":clientId
					},
					dataType:"text",
					success:function(data,textStatus){
						if(data == '0' || sendAnswerTimes > 10)
						{
							for(var i = 0 ; i < msgIds.length ; i++)
								$('span#answer'+msgIds[i]).remove();
							sendAnswerTimes = 0;
						}
						else
							logger('发送答案异常'+data);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown){
	              		logger('发送答案异常'+textStatus);
	        		}
					
				});
			}catch(e){
				showError(e);
				return false ;
			}
		}	
	}
	function sendAnswerBg()
	{
		var answerList = $('div#answerList>span');
		if (answerList.length > 0)
		{
			var answerPair = answerList.get(0);
			var msgId = answerPair.attributes.getNamedItem("msgId").value;
			var answer = answerPair.attributes.getNamedItem("answer").value;
			answer=encodeURI(answer);
			try
			{
				$.ajax({
					type:"post",
					url:"client",
					cache:false,
					timeout:3000,
					data:{
					"actionType":"sendAnswer",
					"answer":answer,
					"msgId":msgId
					},
					dataType:"text",
					success:function(data,textStatus){
						if(data == '0')
						{
							$('span#answer'+msgId).remove();
						}
					},
					error: function(XMLHttpRequest, textStatus, errorThrown){
	        		//TODO: 处理status， http status code，超时 408
	        		// 注意：如果发生了错误，错误信息（第二个参数）除了得到null之外，还可能
	              	//是"timeout", "error", "notmodified" 和 "parsererror"。
	              		logger('发送答案异常'+textStatus);
	        		}
				});
			}catch(e){
				showError(e);
				return false ;
			}
		}
	}
	function sendAnswer(id){
		// 发送答案
		var answer = $('input#answer').val().trim();
		
		var answerList = $('div#answerList');
		var answerPair = '<span id=answer'+id+' msgId='+id+' answer='+answer+' >'+id+':'+answer+',\t</span>';
		answerList.append(answerPair)
		return false;		
	}	

//}());